# -*- coding:utf8 -*-
# !/usr/bin/env python

import re
import string

a_string = string.digits + string.lowercase


def function_e(c):
    c = int(c)
    if c < 26:
        return a_string[c]
    else:
        raise Exception("input error")


def function_r(c, k, r={}):
    c = int(c)
    while (c):
        c -= 1
        r[function_e(c)] = k[c] or function_e(c)
    return r


def function_p(p, r, c=1):
    r_str = ''
    while (c):
        c -= 1
        p_key = re.findall('\w', p)

        r_str = ''
        for num, key in enumerate(p_key):
            r_str += ' ' + r[key]

    return r_str


def parse_cookie(cookie_list):
    assert cookie_list and len(cookie_list) == 6
    p, a, c, k, e, r = cookie_list

    k = re.findall("\'(.*?)\'\.split", k)

    if not k:
        raise Exception("cookie error")
    k = k[0].split("|")

    r = function_r(c, k, r={})

    r_str = function_p(p, r, c=1)

    cookie = re.findall("challenge .*?(\w{40})", r_str)
    if cookie:
        return cookie[0]
    else:
        raise Exception("cookie error")


def kill_cookie(cookie_html):
    tmp_str = re.findall("return p}\((.*?)\)\)</script>", cookie_html)
    tmp_str = tmp_str[0] if tmp_str else ''
    if not tmp_str:
        raise Exception("cookie error")

    cookie_list = tmp_str.split(",")
    return parse_cookie(cookie_list)


if __name__ == "__main__":
    str1 = '<html><body onload="challenge();"><script>eval(function(p,a,c,k,e,r){e=function(c){return c.toString(a)};if(!\'\'.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return\'\\\\w+\'};c=1};while(c--)if(k[c])p=p.replace(new RegExp(\'\\\\b\'+e(c)+\'\\\\b\',\'g\'),k[c]);return p}(\'d 2(){6.l=\\\'m=f; 1-4=o; h=/\\\';k.7.a()};e b(){c.j=\\\'0=p; n-8=9; 5=/\\\';i.3.g()}\',26,26,\'ROBOTCOOKIEID                   |max|challenge_f|location|age|path|document|location|age|600 |reload|challenge|document|function|function|a6b69d80cfcd98f6a9ebfcc388e12a0a137a8a82|reload|path|window|cookie|window|cookie|ROBOTCOOKIEID                   |max|600 |0f22b16a57f907a6cc7be6623b277e73cb2dd855\'.split(\'|\'),0,{}))</script></body></html>'

    print kill_cookie(str1)
